<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta name="baidu-site-verification" content="UqlC4pwKIm">
  <meta name="baidu-site-verification" content="d3U0dGeqGw">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">



  <meta name="google-site-verification" content="1C1XSuJ8TgM2O0mcZvsgzEdy0IdRZOJfxDYPyh18U9Q">














  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">




  
  
  
  

  
    
    
  

  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
      
    

    
  

  
    
    
    <link href="//fonts.cat.net/css?family=Roboto Slab:300,300italic,400,400italic,700,700italic|Roboto Slab:300,300italic,400,400italic,700,700italic|Lobster Two:300,300italic,400,400italic,700,700italic|PT Mono:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/favicon.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="js,闭包,">










<meta name="description" content="javascripthttps://www.cnblogs.com/cxying93/p/6103375.html 什么是闭包？闭包的优缺点？闭包（closure）是javascript的一大难点，也是它的特色。很多高级应用都要依靠闭包来实现。 1、变量作用域 要理解闭包，首先要理解javascript的特殊的变量作用域。 变量的作用域无非就两种：全局变量和局部变量。 javascript语言的特">
<meta name="keywords" content="js,闭包">
<meta property="og:type" content="article">
<meta property="og:title" content="什么是闭包？闭包的优缺点">
<meta property="og:url" content="http://sangmu.wewithwe.com/2018/11/27/闭包/index.html">
<meta property="og:site_name" content="隐久">
<meta property="og:description" content="javascripthttps://www.cnblogs.com/cxying93/p/6103375.html 什么是闭包？闭包的优缺点？闭包（closure）是javascript的一大难点，也是它的特色。很多高级应用都要依靠闭包来实现。 1、变量作用域 要理解闭包，首先要理解javascript的特殊的变量作用域。 变量的作用域无非就两种：全局变量和局部变量。 javascript语言的特">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-11-28T05:49:16.269Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="什么是闭包？闭包的优缺点">
<meta name="twitter:description" content="javascripthttps://www.cnblogs.com/cxying93/p/6103375.html 什么是闭包？闭包的优缺点？闭包（closure）是javascript的一大难点，也是它的特色。很多高级应用都要依靠闭包来实现。 1、变量作用域 要理解闭包，首先要理解javascript的特殊的变量作用域。 变量的作用域无非就两种：全局变量和局部变量。 javascript语言的特">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":true,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: 'undefined',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://sangmu.wewithwe.com/2018/11/27/闭包/">





  <title>什么是闭包？闭包的优缺点 | 隐久</title>
  




<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
            (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
          m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
  ga('create', 'UA-111723881-1', 'auto');
  ga('send', 'pageview');
</script>





</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">隐久</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description"></h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br>
            
            公益404
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://sangmu.wewithwe.com/2018/11/27/闭包/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="隐久">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="隐久">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">什么是闭包？闭包的优缺点</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-11-27T23:55:43+08:00">
                2018-11-27
              </time>
            

            
              <span class="post-meta-divider">|</span>
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-check-o"></i>
              </span>
              
                <span class="post-meta-item-text">更新于&#58;</span>
              
              <time title="更新于" itemprop="dateModified" datetime="2018-11-28T13:49:16+08:00">
                2018-11-28
              </time>
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/categories/JavaScript/" itemprop="url" rel="index">
                    <span itemprop="name">JavaScript</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2018/11/27/闭包/" class="leancloud_visitors" data-flag-title="什么是闭包？闭包的优缺点">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>javascript<br><a href="https://www.cnblogs.com/cxying93/p/6103375.html" target="_blank" rel="noopener">https://www.cnblogs.com/cxying93/p/6103375.html</a></p>
<h1 id="什么是闭包？闭包的优缺点？"><a href="#什么是闭包？闭包的优缺点？" class="headerlink" title="什么是闭包？闭包的优缺点？"></a><a href="https://www.cnblogs.com/cxying93/p/6103375.html" target="_blank" rel="noopener">什么是闭包？闭包的优缺点？</a></h1><p>闭包（closure）是javascript的一大难点，也是它的特色。很多高级应用都要依靠闭包来实现。</p>
<p><strong>1、变量作用域</strong></p>
<p>要理解闭包，首先要理解javascript的特殊的变量作用域。</p>
<p>变量的作用域无非就两种：全局变量和局部变量。</p>
<p>javascript语言的特别之处就在于：<span data-type="color" style="color:rgb(0, 0, 0)"><span data-type="background" style="background-color:rgb(255, 204, 153)">函数内部可以直接读取全局变量，但是在函数外部无法读取函数内部的局部变量。</span></span></p>
<p><span data-type="background" style="background-color:rgb(255, 204, 153)">注意点：在函数内部声明变量的时候，一定要使用var命令。</span>如果不用的话，你实际上声明的是一个全局变量！</p>
<p><strong>2、如何从外部读取函数内部的局部变量？</strong></p>
<p>出于种种原因，我们有时候需要获取到函数内部的局部变量。但是，上面已经说过了，正常情况下，这是办不到的！只有通过变通的方法才能实现。</p>
<p>那就是在函数内部，再定义一个函数。</p>
<blockquote>
<p><span data-type="background" style="background-color:rgb(204, 255, 255)">function f1(){</span><br><span data-type="background" style="background-color:rgb(204, 255, 255)">　　　　var n=999;</span><br><span data-type="background" style="background-color:rgb(204, 255, 255)">　　　　function f2(){</span><br><span data-type="background" style="background-color:rgb(204, 255, 255)">　　　　　　alert(n); // 999</span><br><span data-type="background" style="background-color:rgb(204, 255, 255)">　　　　}</span><br><span data-type="background" style="background-color:rgb(204, 255, 255)">　　}</span><br>在上面的代码中，函数f2就被包括在函数f1内部，这时f1内部的所有局部变量，对f2都是可见的。但是反过来就不行，f2内部的局部变量，对f1就是不可见的。</p>
</blockquote>
<p>这就是Javascript语言特有的<span data-type="background" style="background-color:rgb(255, 204, 153)">&quot;链式作用域&quot;结构（chain scope）</span>，</p>
<p>子对象会一级一级地向上寻找所有父对象的变量。所以，父对象的所有变量，对子对象都是可见的，反之则不成立。</p>
<p>既然f2可以读取f1中的局部变量，那么只要把f2作为返回值，我们不就可以在f1外部读取它的内部变量了吗！</p>
<p><strong>3、闭包的概念</strong></p>
<p>上面代码中的f2函数，就是闭包。</p>
<p>各种专业文献的闭包定义都非常抽象，我的理解是: <span data-type="background" style="background-color:rgb(255, 204, 153)">闭包就是能够读取其他函数内部变量的函数。</span></p>
<p><span data-type="background" style="background-color:rgb(255, 204, 153)"><span data-type="background" style="background-color:rgb(255, 255, 255)">由于在javascript中，只有函数内部的子函数才能读取局部变量，所以说，</span></span>闭包可以简单理解成“定义在一个函数内部的函数“。</p>
<p><span data-type="background" style="background-color:rgb(255, 204, 153)"><span data-type="background" style="background-color:rgb(255, 255, 255)">所以，</span></span>在本质上，闭包是将函数内部和函数外部连接起来的桥梁。</p>
<p><strong> 4、闭包的用途</strong></p>
<p>闭包可以用在许多地方。它的最大用处有两个，<span data-type="background" style="background-color:rgb(255, 204, 153)">一个是前面提到的可以读取函数内部的变量，另一个就是让这些变量的值始终保持在内存中，不会在f1调用后被自动清除。</span></p>
<p>为什么会这样呢？原因就在于f1是f2的父函数，而f2被赋给了一个全局变量，这导致f2始终在内存中，而f2的存在依赖于f1，因此f1也始终在内存中，不会在调用结束后，被垃圾回收机制（garbage collection）回收。</p>
<p>这段代码中另一个值得注意的地方，就是”nAdd=function(){n+=1}”这一行，首先在nAdd前面没有使用var关键字，因此nAdd是一个全局变量，而不是局部变量。其次，nAdd的值是一个匿名函数（anonymous function），而这个匿名函数本身也是一个闭包，所以nAdd相当于是一个setter，可以在函数外部对函数内部的局部变量进行操作。</p>
<p><strong>5、使用闭包的注意点</strong></p>
<p>（1）由于闭包会使得函数中的变量都被保存在内存中，内存消耗很大，所以不能滥用闭包，否则会造成网页的性能问题，在IE中可能导致内存泄露。解决方法是，在退出函数之前，将不使用的局部变量全部删除。</p>
<p>（2）闭包会在父函数外部，改变父函数内部变量的值。所以，如果你把父函数当作对象（object）使用，把闭包当作它的公用方法（Public Method），把内部变量当作它的私有属性（private value），这时一定要小心，不要随便改变父函数内部变量的值。</p>
<p><span data-type="color" style="color:rgb(192, 192, 192)"><span data-type="background" style="background-color:rgb(255, 255, 255)">参考文献：</span></span></p>
<p><span data-type="color" style="color:rgb(192, 192, 192)"><span data-type="background" style="background-color:rgb(255, 255, 255)">　　</span></span><a href="https://www.baidu.com/link?url=wIOdux3T6MbZppYcuQ55MYErvuIo3QmkwlMnFhJ2-S0BwmuJmyUqQSuQc8OudI-HReFTsUNsg6EQCiaumcMjSZOAyDJKIXWrFbkAxHHB98TNpWkNrHdlzm1hmvfeRzTp&amp;wd=&amp;eqid=d5eece060004123a00000003583a30df" target="_blank" rel="noopener">学习Javascript闭包(Closure) - 阮一峰的网络日志</a></p>
<h2 id="深入理解Java闭包概念"><a href="#深入理解Java闭包概念" class="headerlink" title="深入理解Java闭包概念"></a>深入理解Java闭包概念</h2><p>闭包又称词法闭包<br><a href="https://www.cnblogs.com/ssp2110/p/3797666.html" target="_blank" rel="noopener">https://www.cnblogs.com/ssp2110/p/3797666.html</a></p>
<p>闭包最早定义为一种包含&lt;环境成分&gt;和&lt;控制成分&gt;的实体.</p>
<p>解释一：闭包是引用了自由变量的函数，这个被引用的变量将和这个函数一同存在。</p>
<p>解释二：闭包是函数和相关引用环境组成的实体。</p>
<p>注：&lt;自由变量&gt;：除了局部变量的其他变量</p>
<p>简单理解：闭包能够将一个方法作为一个变量去存储，这个方法有能力去访问所在类的自由变量。</p>
<p>Java中闭包实现</p>
<p>关键点：</p>
<p>如何用变量去存储方法？</p>
<p>java中能够保存方法的变量指的就是普通的对象</p>
<p>如何让这个普通对象能够访问所在类的自由变量？</p>
<p>纯天然的解决办法是：内部类。内部类能够访问外部类的所有属性及方法。</p>
<p>隐藏具体实现是内部类的作用之一，如何保证隐藏具体实现的同时还能将闭包传递到外部使用？</p>
<p>让内部类实现通用接口，然后将内部类对象向上转型为接口类型。</p>
<p>上述解决办法就是Java最常用的闭包实现办法（内部类+接口）</p>
<p>下面提供一个简单的实现</p>
<p>[java] view plaincopyprint?<br>public class Milk {</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">public final static String name = &quot;纯牛奶&quot;;//名称  </span><br><span class="line">  </span><br><span class="line">private static int num = 16;//数量  </span><br><span class="line">  </span><br><span class="line">public Milk()  </span><br><span class="line">&#123;  </span><br><span class="line">    System.out.println(name+&quot;：16/每箱&quot;);  </span><br><span class="line">&#125;  </span><br><span class="line">  </span><br><span class="line">/** </span><br><span class="line"> * 闭包 </span><br><span class="line"> * @return 返回一个喝牛奶的动作 </span><br><span class="line"> */  </span><br><span class="line">public Active HaveMeals()  </span><br><span class="line">&#123;  </span><br><span class="line">    return new Active()  </span><br><span class="line">            &#123;  </span><br><span class="line">                public void drink()  </span><br><span class="line">                &#123;  </span><br><span class="line">                    if(num == 0)  </span><br><span class="line">                    &#123;  </span><br><span class="line">                        System.out.println(&quot;木有了，都被你丫喝完了.&quot;);  </span><br><span class="line">                        return;  </span><br><span class="line">                    &#125;  </span><br><span class="line">                    num--;  </span><br><span class="line">                    System.out.println(&quot;喝掉一瓶牛奶&quot;);  </span><br><span class="line">                &#125;  </span><br><span class="line">            &#125;;  </span><br><span class="line">&#125;  </span><br><span class="line">  </span><br><span class="line">/** </span><br><span class="line"> * 获取剩余数量 </span><br><span class="line"> */  </span><br><span class="line">public void currentNum()  </span><br><span class="line">&#123;  </span><br><span class="line">    System.out.println(name+&quot;剩余：&quot;+num);  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>}</p>
<p>/**</p>
<ul>
<li>通用接口<br>  */<br>  interface Active<br>  {<br>  void drink();<br>  }<br>  使用上述实现</li>
</ul>
<p>[java] view plaincopyprint?<br>public class Person {</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">public static void main(String[] args) &#123;  </span><br><span class="line">    //买一箱牛奶  </span><br><span class="line">    Milk m = new Milk();  </span><br><span class="line">      </span><br><span class="line">    Active haveMeals = m.HaveMeals();  </span><br><span class="line">      </span><br><span class="line">    //没事喝一瓶  </span><br><span class="line">    haveMeals.drink();  </span><br><span class="line">    //有事喝一瓶  </span><br><span class="line">    haveMeals.drink();  </span><br><span class="line">      </span><br><span class="line">    //看看还剩多少？  </span><br><span class="line">    m.currentNum();  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>}<br>运行结果</p>
<p>[java] view plaincopyprint?<br>纯牛奶：16/每箱<br>喝掉一瓶牛奶<br>喝掉一瓶牛奶<br>纯牛奶剩余：14<br>上述例子中，通过调用Active的方法实现对Milk私有变量num进行修改。</p>
<p>有时候觉得直接使用set方法也可以直接修改private变量，但是从现实生活中来说让人去执行喝牛奶的动作比牛奶自己动手喝来的合理一些。</p>
<p>总结</p>
<p>1.实际项目中没怎么用过闭包，因此不能对他的好坏进行评论。</p>
<p>2.建议合理的使用闭包，不完全不使用，也不能滥用。</p>
<p>3.特别注意：闭包会导致资源不被回收，如上例，在main方法中将m设为null，使用haveMeals继续调用drink方法仍然会喝掉一瓶牛奶，说明Milk对象并没有被释放掉。</p>

      
    </div>
    
    
    

    

    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    隐久
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://sangmu.wewithwe.com/2018/11/27/闭包/" title="什么是闭包？闭包的优缺点">http://sangmu.wewithwe.com/2018/11/27/闭包/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/js/" rel="tag"># js</a>
          
            <a href="/tags/闭包/" rel="tag"># 闭包</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div id="needsharebutton-postbottom">
            <span class="btn">
              <i class="fa fa-share-alt" aria-hidden="true"></i>
            </span>
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/10/28/HexoEditor/" rel="next" title="HexoEditor">
                <i class="fa fa-chevron-left"></i> HexoEditor
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/11/28/毫秒级从百亿大表任意维度筛选数据，是怎么做到的.../" rel="prev" title="毫秒级从百亿大表任意维度筛选数据，是怎么做到的...">
                毫秒级从百亿大表任意维度筛选数据，是怎么做到的... <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
      <div id="sidebar-dimmer"></div>
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="隐久">
            
              <p class="site-author-name" itemprop="name">隐久</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

			<!--my custom code begin-->
			<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
			<script src="https://cdnjs.cloudflare.com/ajax/libs/velocity/1.5.0/velocity.min.js"></script>
			<script type="text/javascript">
			  $("#sidebar").hover(function(){
				$("#mydivshow").velocity('stop').velocity({opacity: 1});
			  },function(){
				$("#mydivshow").velocity('stop').velocity({opacity: 0});
			  });
			</script>
			<div id="mydivshow" class="mydivshow">
			<!--my custom code end-->
			
          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives">
              
                  <span class="site-state-item-count">6</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">5</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          <div class="links-of-author motion-element">
            
              
                <span class="links-of-author-item">
                  <a href="https://github.com/yourname" target="_blank" title="GitHub">
                    
                      <i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://gitee.com/yourname" target="_blank" title="Gitee">
                    
                      <i class="fa fa-fw fa-glide"></i>Gitee</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:yourname @gmail.com" target="_blank" title="E-Mail">
                    
                      <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://plus.google.com/" target="_blank" title="Google">
                    
                      <i class="fa fa-fw fa-google"></i>Google</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.weibo.com/" target="_blank" title="微博">
                    
                      <i class="fa fa-fw fa-weibo"></i>微博</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.zhihu.com/people/yourname" target="_blank" title="知乎">
                    
                      <i class="fa fa-fw fa-bell"></i>知乎</a>
                </span>
              
            
          </div>

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://me.csdn.net/helloniou" title="CSDN博客主页" target="_blank">CSDN博客主页</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://yingjiu.github.io" title="全球站主页" target="_blank">全球站主页</a>
                  </li>
                
              </ul>
            </div>
          

          <div id="player1" class="aplayer"></div>
<script src="/js/src/APlayer.min.js"></script>
<script type="text/javascript">
var ap = new APlayer({
    element: document.getElementById('player1'),                       // Optional, player element
    narrow: false,                                                     // Optional, narrow style
    autoplay: false,                                                    // Optional, autoplay song(s), not supported by mobile browsers
    showlrc: 0,                                                        // Optional, show lrc, can be 0, 1, 2, see: ###With lrc
    mutex: true,                                                       // Optional, pause other players when this player playing
    theme: '#e6d0b2',                                                  // Optional, theme color, default: #b7daff
    mode: 'random',                                                    // Optional, play mode, can be `random` `single` `circulation`(loop) `order`(no loop), default: `circulation`
    preload: 'metadata',                                               // Optional, the way to load music, can be 'none' 'metadata' 'auto', default: 'auto'
    listmaxheight: '513px',                                             // Optional, max height of play list
    music: {                                                           // Required, music info, see: ###With playlist
        title: '黑色幽默',                                          // Required, music title
        author: 'cover',                          // Required, music author
        url: 'http://www.ytmp3.cn/down/55230.mp3',  // Required, music url
        pic: '/images/visitor.jpg',  // Optional, music picture
    }
});
</script>
        </div>
		<!--my custom code begin-->
		</div>
		<!--my custom code end-->
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#什么是闭包？闭包的优缺点？"><span class="nav-number">1.</span> <span class="nav-text">什么是闭包？闭包的优缺点？</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#深入理解Java闭包概念"><span class="nav-number">1.1.</span> <span class="nav-text">深入理解Java闭包概念</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2017 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">隐久</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count"></span>
  
</div>






  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a></div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
          <span id="scrollpercent"><span>0</span>%</span>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>




  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("", "");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "box";
      
          pbOptions.boxForm = "horizontal";
      
          pbOptions.position = "bottomCenter";
      
          pbOptions.networks = "Weibo,Wechat,Douban,QQZone,Twitter,Facebook";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
  </script>

  

  
  


  
  <script type="text/javascript" src="/js/src/js.cookie.js?v=5.1.3"></script>
  <script type="text/javascript" src="/js/src/scroll-cookie.js?v=5.1.3"></script>


  
  <script type="text/javascript" src="/js/src/exturl.js?v=5.1.3"></script>


  <script src="/js/src/Aplayer-Controler.js"></script>
<div id="AP-controler"></div>
<script type="text/javascript">
var myapc=new APlayer_Controler({
		APC_dom:$('#AP-controler'),
		aplayer:ap, //此为绑定的aplayer对象
		attach_right:false,
		position:{top:'300px',bottom:''},
		fixed:true,
		btn_width:100,
		btn_height:120,
		img_src:['http://oty1v077k.bkt.clouddn.com/bukagirl.jpg',
				'http://oty1v077k.bkt.clouddn.com/jumpgirl.jpg',
				'http://oty1v077k.bkt.clouddn.com/pentigirl.jpg',
				'http://oty1v077k.bkt.clouddn.com/%E8%90%8C1.gif'],
		img_style:{repeat:'no-repeat',position:'center',size:'contain'},
		ctrls_color:'rgba(173,255,47,0.8)',
		ctrls_hover_color:'rgba(255,140,0,0.7)',
		tips_on:true,
		tips_width:140,
		tips_height:25,
		tips_color:'rgba(255,255,255,0.6)',
		tips_content:{},
		timeout:30
	});
</script>
  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>

<!-- 页面点击小红心 -->
<script type="text/javascript" src="/js/src/love.js"></script>



</body>
</html>
